# -*- coding: utf-8 -*-
# @author: chenhuachao
# @time: 2019/3/7
# Servers.py
import sys
from snownlp import SnowNLP
import grpc
import time
from concurrent import futures
import data_pb2
import data_pb2_grpc
import synonyms
from synonyms.jieba import posseg as pseg


_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = "0.0.0.0"
_PORT = "19999"

class RpcServer(data_pb2_grpc.GreeterServicer):
    def GetSummary(self, request, context):
        '''
        获取文章摘要
        :param request:
        :param context:
        :return:
        '''
        code=0
        try:
            s = SnowNLP(request.content)
            abstract = ''.join(s.summary(1))
        except Exception as e:
            abstract = str(e)
            code=1
        return data_pb2.Return(message=abstract,code=code)

    def GetSynonym(self,request,context):
        '''
        获取近义词
        :param request:
        :param context:
        :return:
        '''
        code=0
        try:
            words = request.content
            words_tuple = pseg.lcut(words)
            word_list = []
            for word, flag in words_tuple:
                if flag == 'a' or flag == 'ad' or flag == 'v':  # 词性判断
                    seg_list = (synonyms.nearby(word))[0]
                    if len(seg_list) <= 1:
                        word = word
                    else:
                        word = seg_list[1]
                word_list.append(word)
            content = "".join(word_list)
        except Exception as e:
            content = str(e)
            code=1
        return data_pb2.Return(message=content, code=code)
def server():
    if sys.argv.__len__()>=2:
        _PORT = sys.argv[1]
    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    data_pb2_grpc.add_GreeterServicer_to_server(RpcServer(), grpcServer)
    grpcServer.add_insecure_port("{0}:{1}".format(_HOST, _PORT))
    grpcServer.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        grpcServer.stop(0)


if __name__ == '__main__':
    server()